package bingo.rpc.framework.cluster.impl;

import bingo.rpc.framework.cluster.ClusterStrategy;
import bingo.rpc.framework.model.ProviderService;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 轮询软负载均衡算法实现
 *
 * @author hujinsheng
 * @project bingo
 * @create 2017-12-14 14:29
 **/
public class RoundRobinClusterStrategyImpl implements ClusterStrategy {
    //计数器
    private int index=0;
    private Lock lock=new ReentrantLock();
    @Override
    public ProviderService select(List<ProviderService> providerServices) {
        ProviderService providerService=null;

        try {
            lock.tryLock(10, TimeUnit.MILLISECONDS);
            if(index>=providerServices.size()){
                index=0;
            }
            providerService=providerServices.get(index);
            index++;

        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
        //保证程序健壮性,若未取到服务,则直接取第一个
        if (providerService == null) {
            providerService = providerServices.get(0);
        }


        return providerService;
    }
}
